//
//  STValidateCode.m
//  ShaBaoOnline
//
//  Created by zaoguan_ios_001 on 16/7/12.
//  Copyright © 2016年 com.ShaBaoOnline.www. All rights reserved.
//

#import "STValidateCode.h"
#import "HGNetworkingRequest.h"
#import "MBProgressHUD+KR.h"

@implementation STValidateCode
//获取验证码
+(void)getValidateCodeByPhoneNume:(NSString *)phoneNum andCodeType:(NSString *)codeType{
    NSMutableDictionary *parameter = [NSMutableDictionary dictionary];
    parameter[@"mobile"] = phoneNum;
    parameter[@"type"] = codeType;
    [[HGNetworkingRequest shareRequest] startGetRequest:api_get_validate_code parameter:parameter showNetworkErrorAlert:YES onCompletion:^(id jsonResponse) {
        int result = [[jsonResponse objectForKey:@"result"] intValue];
        if (result== -3) {
            [MBProgressHUD showError:@"已经发送过"];
        }else if(result == 1){
        }else{
            [MBProgressHUD showError:@"获取验证码失败"];
        }
    } onError:^(id jsonResponse) {
        [MBProgressHUD showError:@"暂无网络"];
    }];
}
//按钮倒计时
+(void)timeCuntDown:(UIButton *)codeBt{
    __block int timeout = 60;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0), 1.0*NSEC_PER_SEC, 0);
    dispatch_source_set_event_handler(_timer, ^{
        if (timeout<=0) {
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                [codeBt  setUserInteractionEnabled:YES];
                [codeBt setTitle:@"获取验证码" forState:UIControlStateNormal];
             //   [codeBt setBackgroundColor:PXY_COLORFROMRGB(0x33ccff)];
            });
        }else{
            int seconds = timeout % 60;
            NSString *strTime = [NSString stringWithFormat:@"%.2d",seconds];
            if (timeout == 60) {
                strTime = @"60";
            }
            dispatch_async(dispatch_get_main_queue(), ^{
//                [UIView beginAnimations:nil context:nil];
//                [UIView setAnimationDuration:1];
                [codeBt setTitle:[NSString stringWithFormat:@"%@S后",strTime] forState:UIControlStateNormal];
           //     [codeBt setBackgroundColor:PXY_COLORFROMRGB(0xf4f4f4)];
           //     [UIView commitAnimations];
                [codeBt  setUserInteractionEnabled:NO];
                
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
}
@end
